package com.zjtaixue.usersite.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zjtaixue.usersite.domain.Major;
import com.zjtaixue.usersite.exception.ApplicationException;
import com.zjtaixue.usersite.mapper.ClassMapper;
import com.zjtaixue.usersite.mapper.CollegeMapper;
import com.zjtaixue.usersite.mapper.MajorMapper;
import com.zjtaixue.usersite.page.PageResult;
import com.zjtaixue.usersite.query.MajorQueryObject;
import com.zjtaixue.usersite.service.MajorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service("majorService")
public class MajorServiceImpl implements MajorService {
    @Autowired
    private MajorMapper majorMapper;
    @Autowired
    private CollegeMapper collegeMapper;
    @Autowired
    private ClassMapper classMapper;
    @Override
    public PageResult<JSONObject> listPageResult(MajorQueryObject qo) {
        int count = majorMapper.queryCount(qo);
        if (count > 0) {
            List<Major> majors=majorMapper.query(qo);
            List<JSONObject> jsonObjects=new ArrayList<>();
            for(Major major:majors){
                JSONObject jsonObject=(JSONObject) JSON.toJSON(major);
                jsonObject.put("college",collegeMapper.selectByPrimaryKey(major.getCollegeId()));
                jsonObjects.add(jsonObject);
            }
            return new PageResult<JSONObject>(jsonObjects, qo.getCurrentPage(), count, qo.getPageSize());
        }
        return PageResult.empty(qo.getPageSize());
    }

    @Override
    public int insert(Major major) {
        int count = majorMapper.countByMajorNameAndCollegeId(major.getName(),major.getCollegeId());
        log.info("专业信息是："+major.toString());
        if(count > 0){
            throw new ApplicationException("该学院已经存在相同的专业");
        }
        return majorMapper.insert(major);
    }

    @Override
    public Major getById(Integer id) {
        return majorMapper.selectByPrimaryKey(id);
    }

    @Override
    public void deleteById(Integer id) {
        int count = classMapper.countByMajorId(id);
        if(count > 0){
            Major major=majorMapper.selectByPrimaryKey(id);
            throw new ApplicationException(major.getName()+"存在班级，不能删除！");
    }
        majorMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int update(Major major) {
        int count= majorMapper.countByMajorNameAndCollegeId(major.getName(),major.getCollegeId());
        if(count>0){
            throw new ApplicationException("该学院已经存在相同的专业");
        }
        return majorMapper.updateByPrimaryKey(major);
    }

    @Override
    public List<Major> listAllMajors() {
        return majorMapper.selectAll();
    }
}
